package com.example.demo.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.mvc.method.RequestMappingInfo;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Map;
import java.util.Set;

@Slf4j
@RestController
@RequestMapping("/rest")
public class ReqCollectController {
    @Value("${spring.application.name:unname}")
    String applicationName;
    @Autowired
    WebApplicationContext applicationContext;
    @RequestMapping("/getall")
    public void getAllUrl(HttpServletResponse response) throws IOException {
        RequestMappingHandlerMapping mapping = applicationContext.getBean(RequestMappingHandlerMapping.class);
        //获取url与类和方法的对应信息
        Map<RequestMappingInfo, HandlerMethod> map = mapping.getHandlerMethods();
        response.setHeader("Content-Disposition", "attachment;filename=" + applicationName+".sql");
        response.setContentType("application/octet-stream");
        ServletOutputStream outputStream = response.getOutputStream();
        outputStream.write("DROP TABLE  IF EXISTS t_urls; \n".getBytes(StandardCharsets.UTF_8));
        outputStream.write("CREATE TABLE `bdap`.`t_urls` ( `url` VARCHAR(300), `methods` VARCHAR(300) ); \n".getBytes(StandardCharsets.UTF_8));
        for (RequestMappingInfo info : map.keySet()){
            //获取url的Set集合，一个方法可能对应多个url 、methos
            Set<RequestMethod> methods = info.getMethodsCondition().getMethods();
            StringBuffer methodSB = new StringBuffer(",");
            for (RequestMethod method : methods) {
                methodSB.append(method.toString()).append(",");
            }
            Set<String> patterns = info.getPatternsCondition().getPatterns();
            for (String url : patterns) {
                outputStream.write(("INSERT INTO t_urls VALUES ('/"+applicationName+url+"','"+methodSB.toString()+"');\n").getBytes(StandardCharsets.UTF_8));
            }

        }
        outputStream.flush();
    }

}
